package cn.cs.mathgo.sso.server;

import cn.cs.mathgo.admin.modules.sys.entity.SysUserEntity;
import cn.cs.mathgo.admin.modules.sys.feign.UserFeignClient;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
   @Autowired
   private UserFeignClient userFeignClient;
   @Autowired(required = false)
   private PasswordEncoder passwordEncoder;
    /**
     * 自定义验证方式
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        R auth = userFeignClient.getByName(username);
        if (auth == null || (Integer) auth.get("code") == -1 || auth.get("user") == null) {
            throw new BadCredentialsException("没有找到用户");
        }
        JSONObject object = new JSONObject(auth.get("user"));

        SysUserEntity userEntity = JSONUtil.toBean(object, SysUserEntity.class);
        if (userEntity.getStatus() == 0) {
            throw new BadCredentialsException("对不起，该账号被禁用");
        }
        //加密过程在这里体现
        if (!StringUtils.equalsIgnoreCase(passwordEncoder.encode(password + "," + userEntity.getSalt()), userEntity.getPwd())) {
            throw new BadCredentialsException("Wrong password.");
       }

            User user = new User(username, userEntity.getPwd(), AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
            Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
            return new UsernamePasswordAuthenticationToken(user, password, authorities);
    }

    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }

}